package cn.fjc920.siaa

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.Button
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import cn.fjc920.siaa.activitys.HomePageActivity
import cn.fjc920.siaa.activitys.LoginActivity
import cn.fjc920.siaa.activityutils.BaseActivity
import cn.fjc920.siaa.internetUtils.OkhttpUtils
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.Request
import org.jsoup.Jsoup
import java.io.IOException
import java.util.zip.Inflater

class MainActivity : BaseActivity() {

    private lateinit var userName: String
    private lateinit var password: String
    private lateinit var map: HashMap<String, String>
    private lateinit var context: Context
    private lateinit var url: String
    private lateinit var sp: SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        init()
        initUserData()
    }

    private fun init(){

        context = this
        url = "${OkhttpUtils.url}login"

        if (isDarkTheme(this)) {
            img_logo.setImageResource(R.mipmap.siaa_logo_bai)
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun initUserData() {

        sp = getSharedPreferences("userData", Context.MODE_PRIVATE).apply {
            if (getBoolean("agree",false)) {
                userName = getString("userName", "")!!
                password = getString("password", "")!!
                if (userName.length > 1 && password.length > 5) {
                    login()
                } else {
                    LoginActivity.actionStart(context)
                    finish()
                }
            }else {
                isAuthorized()
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    @SuppressLint("MissingInflatedId", "InflateParams")
    private fun isAuthorized() {
        val view = layoutInflater.inflate(R.layout.dialog_permissions, null)
        view.findViewById<Button>(R.id.btn_reject).setOnClickListener {
            finish()
        }
        view.findViewById<Button>(R.id.btn_agree).setOnClickListener {
            sp.edit {
                putBoolean("agree",true)
            }
            //判断是否获取了权限，如果未获取则向用户申请授权
            if (ContextCompat.checkSelfPermission(context,
                    Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                    arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
            } else {
                initUserData()
            }
        }
        AlertDialog.Builder(context).apply {
            setView(view)
            setCancelable(false)
            create()
            show()
        }
    }

    //处理授权或拒绝授权时的回调
    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        when (requestCode) {
            1 -> {
                if (grantResults.isNotEmpty() &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initUserData()
                } else {
                    //如果拒绝授权就提示用户
                    Toast.makeText(this, "未授予通知权限，可在设置中手动开启！",Toast.LENGTH_SHORT).show()
                    initUserData()
                }
            }
        }
    }

    private fun login() {

        OkhttpUtils.getAsync(url, object : OkhttpUtils.DataCallBack {
            override fun requestFailure(request: Request?, e: IOException?) {
                Toast.makeText(context, "登录失败请检查网络", Toast.LENGTH_SHORT).show()
            }

            override fun requestSuccess(result: String?) {

                //获取_csrf
                val doc = Jsoup.parse(result!!)
                val input = doc.select("input[type=hidden]")
                val element = input[0]
                val _csrf = element.attr("value")
                map = HashMap()
                map["username"] = userName
                map["password"] = password
                map["_csrf"] = _csrf
                map["remember-me"] = "on"

                OkhttpUtils.postAsync(url, map, object : OkhttpUtils.DataCallBack {

                    override fun requestFailure(request: Request?, e: IOException?) {
                        Toast.makeText(context, "登录超时，请检查网络", Toast.LENGTH_SHORT).show()
                    }

                    @SuppressLint("CommitPrefEdits")
                    override fun requestSuccess(result: String) {
                        val doc1 = Jsoup.parse(result)
                        //获取用户名
                        val un = doc1.getElementById("avatar")!!.text()

                        if (userName == un) {
                            HomePageActivity.actionStart(context)
                            finish()
                        } else {
                            Toast.makeText(context, "登录已过期,请重新登录", Toast.LENGTH_SHORT).show()
                            LoginActivity.actionStart(context)
                            finish()
                            sp.edit().apply {
                                remove("userName")
                                remove("password")
                            }
                            OkhttpUtils.cookieStore.clear()
                        }
                    }
                })
            }
        })
    }
}